import React, { useState, useEffect, useCallback } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { UserCheck, RefreshCw, CheckCircle } from 'lucide-react';
import { roleApi } from '@/services/api';

const RoleSwitchDialog = ({ open, onOpenChange, onRoleSwitch }) => {
  const [roles, setRoles] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isSwitching, setIsSwitching] = useState(false);
  const [currentRoleId, setCurrentRoleId] = useState(null);

  // 获取当前用户的角色列表
  const fetchUserRoles = useCallback(async () => {
    if (!open) return; // 只有在对话框打开时才获取数据
    
    setIsLoading(true);
    try {
      const response = await roleApi.getSelfRoles();
      if (response.code === "200" && response.msg === "success" && response.data) {
        setRoles(response.data);
        
        // 从本地存储获取当前角色ID
        const storage = localStorage.getItem('authToken') ? localStorage : sessionStorage;
        const userInfo = storage.getItem('userInfo');
        if (userInfo) {
          try {
            const userData = JSON.parse(userInfo);
            setCurrentRoleId(userData.currentRoleId);
          } catch (error) {
            console.error('解析用户信息失败:', error);
          }
        }
      }
    } catch (error) {
      console.error('获取角色列表失败:', error);
      // 如果获取失败，显示错误提示
      setRoles([]);
    } finally {
      setIsLoading(false);
    }
  }, [open]);

  // 切换角色
  const handleRoleSwitch = useCallback(async (roleId) => {
    if (roleId === currentRoleId) {
      // 如果是当前角色，直接关闭对话框
      if (onOpenChange) {
        onOpenChange(false);
      }
      return;
    }

    setIsSwitching(true);
    try {
      const response = await roleApi.switchRole(roleId);
      if (response.code === "200" && response.msg === "success" && response.data) {
        const { accessToken, roleId: newRoleId, roleName } = response.data;
        
        // 更新浏览器缓存的token
        const storage = localStorage.getItem('authToken') ? localStorage : sessionStorage;
        storage.setItem('authToken', accessToken);
        
        // 更新用户信息中的角色信息
        const userInfo = storage.getItem('userInfo');
        if (userInfo) {
          try {
            const userData = JSON.parse(userInfo);
            userData.currentRoleId = newRoleId;
            userData.currentRoleName = roleName;
            storage.setItem('userInfo', JSON.stringify(userData));
          } catch (error) {
            console.error('更新用户信息失败:', error);
          }
        }
        
        // 更新当前角色ID
        setCurrentRoleId(newRoleId);
        
        // 通知父组件角色已切换
        if (onRoleSwitch) {
          onRoleSwitch(newRoleId, roleName);
        }
        
        // 关闭对话框
        if (onOpenChange) {
          onOpenChange(false);
        }
        
        // 显示成功提示
        console.log(`角色切换成功：${roleName}`);
      } else {
        throw new Error(response.msg || '角色切换失败');
      }
    } catch (error) {
      console.error('角色切换失败:', error);
      alert('角色切换失败，请稍后重试');
    } finally {
      setIsSwitching(false);
    }
  }, [currentRoleId, onRoleSwitch, onOpenChange]);

  // 处理对话框关闭 - 修复关键问题
  const handleDialogClose = useCallback((newOpen) => {
    // 确保在切换过程中不能关闭对话框
    if (isSwitching) {
      return;
    }
    
    // 重置所有状态
    if (!newOpen) {
      setRoles([]);
      setIsLoading(false);
      setCurrentRoleId(null);
    }
    
    // 调用父组件的关闭处理函数
    if (onOpenChange) {
      onOpenChange(newOpen);
    }
  }, [isSwitching, onOpenChange]);

  // 当对话框打开时获取角色列表
  useEffect(() => {
    if (open) {
      fetchUserRoles();
    }
  }, [open, fetchUserRoles]);

  // 确保对话框关闭时清理状态
  useEffect(() => {
    if (!open) {
      // 延迟清理状态，确保动画完成
      const timer = setTimeout(() => {
        setRoles([]);
        setIsLoading(false);
        setIsSwitching(false);
        setCurrentRoleId(null);
      }, 200);
      
      return () => clearTimeout(timer);
    }
  }, [open]);

  return (
    <Dialog 
      open={open} 
      onOpenChange={handleDialogClose}
      // 添加这些属性确保对话框正确处理
      modal={true}
    >
      <DialogContent 
        className="sm:max-w-md"
        // 防止对话框内容区域的事件冒泡
        onPointerDownOutside={(e) => {
          if (isSwitching) {
            e.preventDefault();
          }
        }}
        onEscapeKeyDown={(e) => {
          if (isSwitching) {
            e.preventDefault();
          }
        }}
      >
        <DialogHeader>
          <DialogTitle className="flex items-center space-x-2">
            <UserCheck className="w-5 h-5" />
            <span>切换角色</span>
          </DialogTitle>
        </DialogHeader>
        
        <div className="py-4">
          {isLoading ? (
            <div className="flex items-center justify-center py-8">
              <div className="w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin mr-3"></div>
              <span className="text-material-grey-600">加载角色列表中...</span>
            </div>
          ) : roles.length > 0 ? (
            <div className="space-y-3">
              <p className="text-sm text-material-grey-600 mb-4">
                选择要切换到的角色：
              </p>
              {roles.map((role) => (
                <div
                  key={role.roleId}
                  className={`p-4 border rounded-lg cursor-pointer transition-colors ${
                    role.roleId === currentRoleId
                      ? 'border-primary bg-primary/5'
                      : 'border-material-grey-200 hover:border-primary/50 hover:bg-primary/5'
                  } ${isSwitching ? 'pointer-events-none opacity-50' : ''}`}
                  onClick={() => !isSwitching && handleRoleSwitch(role.roleId)}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <div className="w-10 h-10 bg-gradient-to-br from-primary/20 to-primary/30 rounded-lg flex items-center justify-center">
                        <UserCheck className="w-5 h-5 text-primary" />
                      </div>
                      <div>
                        <h4 className="font-medium text-material-grey-900">{role.roleName}</h4>
                        <p className="text-sm text-material-grey-600">代码: {role.roleCode}</p>
                        {role.rolePath && (
                          <p className="text-xs text-material-grey-500">路径: {role.rolePath}</p>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center space-x-2">
                      {role.roleId === currentRoleId && (
                        <Badge className="bg-green-100 text-green-800">
                          <CheckCircle className="w-3 h-3 mr-1" />
                          当前角色
                        </Badge>
                      )}
                      {role.isEnabled === 1 ? (
                        <Badge className="bg-blue-100 text-blue-800">启用</Badge>
                      ) : (
                        <Badge variant="secondary">禁用</Badge>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8">
              <UserCheck className="w-12 h-12 mx-auto mb-4 text-material-grey-400" />
              <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                暂无可用角色
              </h3>
              <p className="text-material-grey-500">
                您当前没有可切换的角色
              </p>
            </div>
          )}
        </div>
        
        <div className="flex justify-end space-x-3">
          <Button 
            variant="outline" 
            onClick={() => handleDialogClose(false)} 
            disabled={isSwitching}
          >
            取消
          </Button>
          {!isLoading && roles.length > 0 && (
            <Button 
              variant="outline" 
              onClick={fetchUserRoles} 
              disabled={isSwitching}
            >
              <RefreshCw className="w-4 h-4 mr-2" />
              刷新
            </Button>
          )}
        </div>
        
        {isSwitching && (
          <div className="absolute inset-0 bg-white/80 flex items-center justify-center rounded-lg">
            <div className="flex items-center space-x-3">
              <div className="w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin"></div>
              <span className="text-material-grey-700">切换中...</span>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
};

export default RoleSwitchDialog;
